#pragma once
#include<iostream>
#include <netinet/in.h>
#include<string>
#include <sys/socket.h>
#include<vector>
#include"Log.hpp"
#include"Mutex.hpp"
#include"InetAddr.hpp"
#include<algorithm>


using namespace MutexModule;
using namespace LogModule;


class Route 
{
public:
    Route()
    {
    }

    void MessageRoute(int sockfd, const std::string& message, InetAddr& peer)
    {
        LockGuard lockguard(Mutex);
        
        if(!IsExist(peer))
        {
            AddUser(peer);
        }

        std::string send_message = peer.StringAddr() + "#" + message;

        for(auto& user : _online_user)
        {
            sendto(sockfd, send_message.c_str(),send_message.size(),0,(const struct sockaddr*)&user.NetAddr(),sizeof(user.NetAddr()));
        }

        if(message == "QUIT")
        {
            LOG(LogLevel::INFO)<<"退出一个在线用户： "<<peer.StringAddr();
            DeleteUser(peer);
        }
    }

    ~Route()
    {
    }
private:

    void AddUser(InetAddr &peer)
    {
        LOG(LogLevel::INFO)<<"新增在线用户:  "<< peer.StringAddr();
        _online_user.push_back(peer);
    }

    void DeleteUser(InetAddr& peer)
    {
        for(auto iter = _online_user.begin(); iter != _online_user.end(); iter++)
        {
            if(*iter == peer)
            {
                LOG(LogLevel::INFO)<<"删除在线用户:  "<< peer.StringAddr();
                _online_user.erase(iter);
                break;
            }
        }
    }

    bool IsExist(InetAddr& peer)
    {
        // for(auto& user : _online_user)
        // {
        //     if(user == peer)
        //     return true;
        // }
        // return false;

        auto it = std::find(_online_user.begin(), _online_user.end(), peer);
        return it != _online_user.end();
    
    }

    std::vector<InetAddr> _online_user;
    Mutex _mutex;
};